package com.edu.controller.book.category;

import com.edu.dto.ResultDto;
import com.edu.entity.CategoryEntity;
import com.edu.service.CategoriesService;
import com.edu.service.impl.CategoriesServiceImpl;
import com.edu.utils.ReturnCode;
import com.edu.utils.ServletHelper;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * com.edu.controller.book
 * 2024/7/4 21:02
 *
 * @author Fancy
 * @version 1.0
 */
@WebServlet("/categories")
public class CategoryController extends HttpServlet {
    CategoriesService categoriesService = new CategoriesServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        List<CategoryEntity> allCategory =  categoriesService.getAllCategory();
        if (allCategory != null) {
            String rst = ResultDto.success(allCategory);
            resp.setStatus(HttpServletResponse.SC_OK);
            resp.getWriter().write(rst);
        } else {
            String rst = ResultDto.fail(ReturnCode.INTERNAL_SERVER_ERROR.getCode(), "内部错误");
            resp.setStatus(HttpServletResponse.SC_OK);
            resp.getWriter().write(rst);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        CategoryEntity categoryEntity = ServletHelper.getRequestBodyAsObject(req, CategoryEntity.class);
        System.out.println(categoryEntity.toString());
        int categoryId = categoriesService.addCategory(categoryEntity);
        HashMap<String, Integer> categoryIdMap = new HashMap<String, Integer>();
        categoryIdMap.put("categoryId", categoryId);

        if(categoryId < 0){
            String rst = ResultDto.fail(ReturnCode.INTERNAL_SERVER_ERROR.getCode(), "添加失败");
            resp.setStatus(HttpServletResponse.SC_OK);
            resp.getWriter().write(rst);
        } else {
            String rst = ResultDto.success(categoryIdMap);
            resp.setStatus(HttpServletResponse.SC_OK);
            resp.getWriter().write(rst);
        }
    }
}
